package org.example.java_gobang.game;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;
//用户在线状态的管理器
@Component
public class OnlineUserManager {
    private ConcurrentHashMap<Integer, WebSocketSession> gameHall = new ConcurrentHashMap<>();
    private ConcurrentHashMap<Integer, WebSocketSession> gameRoom = new ConcurrentHashMap<>();

    public void enterGameHall(int userId, WebSocketSession session) {
        gameHall.put(userId, session);
    }

    // 只有当前⻚⾯退出的时候, 能销毁⾃⼰的 session
    // 避免当⼀个 userId 打开两次 游戏⻚⾯, 错误的删掉之前的会话的问题.
    public void exitGameHall(int userId) {
        gameHall.remove(userId);
    }

    public WebSocketSession getSessionFromGameHall(int userId) {
        return gameHall.get(userId);
    }

    public void enterGameRoom(int userId, WebSocketSession session) {
        gameRoom.put(userId, session);
    }

    public void exitGameRoom(int userId) {
        gameRoom.remove(userId);
    }

    public WebSocketSession getSessionFromGameRoom(int userId) {
        return gameRoom.get(userId);
    }
    //给 MatchAPI注⼊OnlineUserManager
    @Component
    public class MatchAPI extends TextWebSocketHandler {
        @Autowired
        private OnlineUserManager onlineUserManager;
    }
}

